<?php

namespace app\api\controller;
use app\admin\model\CouponRecord;
use app\common\controller\Api;

/**
 * 优惠券
 */
class Coupon extends Api
{
    protected $noNeedLogin = [''];
    protected $noNeedRight = '*';
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Coupon();
    }

    /*
   * 可领优惠券列表
   */
    public function coupon_list(){
        $list = \app\admin\model\Coupon::field('money,min_money,id,name,start_time,end_time')
            ->where(function ($query)  {
                $query->where('assign_type', 'none')
                    ->whereOr(function ($query)  {
                        $query->where('assign_type', 'users')
                            ->whereRaw('FIND_IN_SET(:user_id, assign_user_ids)');
                    });
            })
            ->bind(['user_id' =>  $this->auth->id])
            ->whereNull('deletetime')
            ->where('status','=',1)
            ->order('id desc')
            ->field('money,min_money,id,name')
            ->paginate(10);
        foreach ($list as $item) {
            $item['expire_time_text']=date('Y.m.d', $item['start_time']).'-'.date('Y.m.d', $item['end_time']);
            $item['money']=round($item['money']);
        }
        $this->success('请求成功', $list);

    }

    /**
     * 领取优惠券
     */
    public function takeCoupon()
    {
        $coupon_id = input('coupon_id/d', 0);
        $record    = \app\admin\model\Coupon::takeCoupon($coupon_id, $this->auth->id);
        $this->success('领取成功', $record);
    }

    /*
     * 券包
     */
    public function coupon_record_list(){
        $status = input('status');
        $query = CouponRecord::where(function($query) use ($status) {
            if($status!==null&&$status!==""){
                $query->where('status', $status);
            }
        });
        $query->where('user_id', $this->auth->id);
        $list = $query->field('id,name,ROUND(money,2) AS money,min_money,expire_time,status,createtime')->order('id desc')->paginate(10);

        foreach ($list as $item) {
            $item['expire_time_text']=date('Y.m.d', $item['createtime']).'-'.date('Y.m.d', $item['expire_time']);
            $item['money']=round($item['money']);
        }
        $this->success('请求成功', $list);
    }

    //可用优惠券列表
    public function coupon_record(){

        $list = CouponRecord::field('id,name,ROUND(money,2) AS money,min_money,expire_time,status,createtime')
            ->where('user_id', $this->auth->id)->where('status', 0)
            ->where('min_money', 'elt',input('price'))
            ->order('id desc')->select();

        foreach ($list as $item) {
            $item['expire_time_text']=date('Y.m.d', $item['createtime']).'-'.date('Y.m.d', $item['expire_time']);
        }
        $this->success('请求成功', $list);
    }


}
